package com.iweb.servlet.front;

import com.iweb.constant.ProductAction;
import com.iweb.entity.Product;
import com.iweb.entity.ReturnData;
import com.iweb.service.ProductService;
import com.iweb.service.impl.ProductServiceImpl;
import com.iweb.servlet.BaseServlet;
import com.iweb.util.StringHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author jay
 * @date 2021/9/13
 * @description
 */
@WebServlet(name = "frontProductServlet", urlPatterns = {"/front/product.do"})
public class ProductServlet extends BaseServlet {

    private ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if (ProductAction.TYPEONELIST.equals(action)) {
            // 获取一级分类下的商品列表
            listTypeOneProduct(req, resp);
            return;
        }
    }

    /**
     * 获取一级分类下的商品列表
     *
     * @param req
     * @param resp
     */
    private void listTypeOneProduct(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ReturnData returnData = new ReturnData();
        try {
            String sId = req.getParameter("typeOneId");
            Integer typeOneId = null;
            String sRows = req.getParameter("rows");
            Integer rows = null;
            if (StringHelper.isEmpty(sId)) {
                returnData.success(null);
                // 输出
                this.output(returnData, resp);
            }
            typeOneId = Integer.valueOf(sId);
            if (StringHelper.isEmpty(sRows)) {
                rows = 8;
            }

            // 查询数据
            List<Product> productList =
                    productService.findListByTypeOne(typeOneId, rows);
            returnData.success(productList);
            this.output(returnData, resp);
        } catch (Exception e) {
            e.printStackTrace();
            returnData.error(e.getMessage());
            // 输出
            this.output(returnData, resp);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
